package com.jandar.spider.schedule;

import com.jandar.spider.config.SeleniumConfig;
import com.jandar.spider.config.property.Spider;
import com.jandar.spider.config.property.SpiderConfig;
//import com.jandar.spider.enums.PunishAreaEnum;
import com.jandar.spider.service.PunishService;
import com.jandar.spider.service.PunishStatisticsService;
import com.jandar.spider.task.PunishTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
public class PunishSchedule {
    @Autowired
    private PunishTask punishTask;
    @Autowired
    private SpiderConfig spiderConfig;
    @Autowired
    private SeleniumConfig seleniumConfig;
    @Autowired
    private PunishStatisticsService punishStatisticsService;

    @Scheduled(cron = "${property.spider.cron}")
    public void exec() {
        if (spiderConfig.getSpider().getPunish().getDailyTask() && !PunishTask.run.get()) {
            start();
        }
    }

    private void start() {
        try {
//            Runtime.getRuntime().exec("killall chromedriver");
            Runtime.getRuntime().exec("taskkill /f /im chromedriver.exe /t");
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        punishStatisticsService.sendEmailByArea(PunishAreaEnum.XC.getName());
//        punishStatisticsService.sendEmailByArea(PunishAreaEnum.GS.getName());
        String[] area = spiderConfig.getSpider().getPunish().getArea();
        Arrays.stream(area).forEach(a -> {
            punishStatisticsService.sendEmailByArea(a);
        });
        String[] url = spiderConfig.getSpider().getPunish().getUrl();

        for (int i = 0; i < url.length; i++) {
            punishTask.producer(seleniumConfig.init(), url[i]);
        }
        punishTask.consumer();
    }
}
